#include "perspective_view.h"
#include "display_list_utils.h"

PerspectiveView::PerspectiveView(Rectangle viewport,GLuint axisHandle,GLuint gridHandle,PerspectiveModel& pModel)
	: 	View(viewport),
		pModel(pModel){
	hAxis = axisHandle;
	hGrid = gridHandle;
}

PerspectiveView::~PerspectiveView(){
}

void PerspectiveView::setEnv(){
	glViewport ((GLint) viewport.x1,(GLint) viewport.y1, (GLsizei) viewport.width(), (GLsizei) viewport.height());
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();
	gluPerspective(60.0, (GLfloat) viewport.width()/(GLfloat) viewport.height(), 0.10, 100.0);
}

void PerspectiveView::display(){
	setEnv();

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	camera.applyCamera();

	glCallList(hAxis);
	glCallList(hGrid);

	glDisable(GL_LIGHTING);
	drawColumns();

	glPushMatrix();
		//glScalef(1.02f,1.02f,1.0f);
		drawRail(pModel.getRailPoints());
	glPopMatrix();
	/*glPushMatrix();
		glScalef(0.97f,0.97f,1.0f);
		drawRail(pMo-railHeightdel.getRailPoints());
	glPopMatrix();*/
	drawCurveShadow();
	glEnable(GL_LIGHTING);
}

void PerspectiveView::drawColumns(){
	std::vector<Column>::iterator it = pModel.getColumns().begin();
	for(;it!=pModel.getColumns().end();++it){
		//(it->drawColumn());
		glPushMatrix();
			glTranslatef((*it).getPosition().x1,(*it).getPosition().x2,0);
			glRotatef((*it).getTheta(),0,0,1);
			glScalef((*it).getDepth(),(*it).getWidth(),(*it).getHigh());
			DisplayListsUtils::drawHalfColumn();
			glScalef(1.0,-1.0,1.0);
			DisplayListsUtils::drawHalfColumn();
		glPopMatrix();
	}
}

void PerspectiveView::drawCurveShadow(){
	std::vector<Point>::const_iterator it=pModel.pointBegin();

	glColor3f(0.0f,1.0f,0.0f);
	glBegin(GL_LINE_LOOP);
	for(;it!=pModel.pointEnd();++it){
		glVertex2f(it->x1,it->x2);
	}
	glEnd();
}

void PerspectiveView::drawRail(std::vector<Point>& v){
	if(v.size()){
		Point* pointer = v._M_impl._M_start;
		for(unsigned int c=0;c<v.size();c++,pointer+=4){
			DisplayListsUtils::drawCube(pointer);
			if(c==pModel.pointSize()-2)
				break;
		}

		// El primero con el ultimo
		Point points[8]={ 	v._M_impl._M_finish[-4],v._M_impl._M_finish[-3],
							v._M_impl._M_finish[-2],v._M_impl._M_finish[-1],
							v._M_impl._M_start[0],v._M_impl._M_start[1],
							v._M_impl._M_start[2],v._M_impl._M_start[3] };

		DisplayListsUtils::drawCube(points);
	}
}

void PerspectiveView::update(Observer* observer){
}
